home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 826 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: crl.crl.com!not-for-mail
  2. From: bobfry@crl.com (Robert Fry)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: To malloc (new) or not to malloc? When is the question.
  5. Date: 9 Jan 1996 08:59:51 -0800
  6. Organization: CRL Dialup Internet Access
  7. Message-ID: <4cu6u7$btf@crl.crl.com>
  8. References: <4ctvk3$ort@maverick.tad.eds.com>
  9. NNTP-Posting-Host: crl.com
  10.  
  11. fignet05.darrins@eds.com (Darrin Smith) writes:
  12.  
  13. >Why is it that you can do something like the following:
  14.  
  15. >     char *x;
  16.  
  17. >     x="Some really long string with no particular meaning";
  18.  
  19. >and have no problems, but can't (safely) do something like this:
  20.  
  21. >    struct st1{char one[10];
  22. >                   char two[20];
  23. >                   char three[10];
  24. >          };
  25.  
  26. >    st1 *sptr;    //or struct st1 *sptr in C instead of C++
  27.  
  28. >    sptr=fread(....);
  29.  
  30. >What is going on here?  Why isn't memory set aside for st1 *sptr just as 
  31. >it is for char *x?  Before I did the new (or malloc) it seemed as though 
  32. >my program was getting written over!
  33.  
  34. Actually, memory is not being set aside for x. What the assignment does 
  35. is set x to point to that string of characters, which are explicitly 
  36. included in your source file. And, in fact, I don't believe you are 
  37. guaranteed to be able to write into that space by the ANSI standard. 
  38. (However, I also believe many compilers will allow you to do so).
  39.  
  40. In your second example, you never defined a place for sptr to point to, 
  41. so it has some uninitialized value. This is usually something that does 
  42. VERY BAD THINGS. In your first example, you have initialized x to point 
  43. to a well-defined place.
  44.  
  45. Does this help? Feel free to send email for further clarification.
  46.  
  47.   Bob
  48.